package com.watson.juc.testlist;

import java.util.concurrent.RecursiveTask;

/**
 * @author watson
 * @date 2021/7/30 17:21
 * @Description: TODO
 **/
public class ForkJoinDemo extends RecursiveTask<Long> {
    private static final long serialVersionUID = -7106284124774532270L;
    private Long start;
    private Long end;
    //临界值
    private Long temp = 10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    //计算方法
    @Override
    protected Long compute() {
        if (end - start < temp) {
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            // 中间值
            Long middle = (start + end) / 2;
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            //拆分任务，把任务压入队列
            task1.fork();
            ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end);
            task2.fork();
            return task1.join() + task2.join();
        }

    }
}
